<?php
/**
 * FastApp.
 * 1/17/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Fastapp\Api\Service\Pay;

use App\Fastapp\Api\Service\Account\AccountSettingService;
use App\Fastapp\Exception\TipException;
use App\Fastapp\Model\AccountPayInfo;
use App\Fastapp\Model\AccountWalletLog;

/**
 * 提现验证
 * @package App\Fastapp\Api\Service
 */
class ValidateWithdrawal
{
    public static function validate(int $uid): bool
    {
        $account_type = get_user_cache('type', $uid);
        $method = 'v' . $account_type;
        if (!method_exists(self::class, $method)) return true;
        return self::$method($uid);
    }

    public static function v700001(int $uid = 0): bool
    {
        $uid = $uid ?: get_uid();
        $config = AccountSettingService::config($uid);
        if (isset($config['withdrawal_recharge_rate'])) {
            $withdrawal_recharge_rate = $config['withdrawal_recharge_rate'];
            if (!$withdrawal_recharge_rate) return true;
        } else $withdrawal_recharge_rate = api_cache()->getAppSetting(get_user_cache('type'))['withdrawal_recharge_rate'];
        $recharge_amount = AccountWalletLog::query()->where(['user_id' => $uid, 'type' => AccountWalletLog::RECHARGE])->sum('amount');
        if (!$recharge_amount) throw new TipException(fastapp_t('account.bill_log_not_enough'));
        $use_amount = AccountWalletLog::query()->where(['user_id' => $uid, 'type' => AccountWalletLog::USE_BALANCE])->sum('amount');
        if (bccomp(bcdiv($use_amount, $recharge_amount, 2), $withdrawal_recharge_rate, 2) != 1) throw new TipException(fastapp_t('account.bill_log_not_enough'));
        return true;
    }

    public static function withdrawal(array $data, &$payinfo): bool
    {
        $account_type = get_user_cache('type', $data['user_id']);
        $method = 'w' . $account_type;
        if (!method_exists(self::class, $method)) return true;
        $payinfo = AccountPayInfo::query()->where(['id' => $data['pay_info_id'], 'user_id' => $data['user_id']])->firstOrFail();
        return self::$method($data, $payinfo);
    }

    public static function w700001(array $data, AccountPayInfo $payinfo): bool
    {
        if (!$payinfo->is_lock) {
            if (AccountPayInfo::query()->where([
                'account_type' => $payinfo->account_type,
                'type' => $payinfo->type,
                'no' => $payinfo->no,
                'is_lock' => 1
            ])->where('user_id', '!=', $payinfo->user_id)->exists()) throw new TipException(fastapp_t('account.withdrawal_account_used'));
        }
        return true;
    }
}